<template>
  <div class="main-container">
    <!-- 面包屑 -->
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>生产派工管理</el-breadcrumb-item>
        <el-breadcrumb-item>生产通知</el-breadcrumb-item>
        <el-breadcrumb-item>派工详情</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- 产品信息============================================================================================= -->
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <div class="pt30 mb20">
      <el-table border stripe :data="productDetil" row-key="producingId">
        <el-table-column prop="wNumber" label="产品工号" align="center" width="90"></el-table-column>
        <el-table-column prop="noticeNumber" label="通知单号" align="center" width="90"></el-table-column>
        <el-table-column prop="sequenceId" label="序列号" align="center" width="70"></el-table-column>
        <el-table-column prop="productName" label="品名" align="center" width="150"></el-table-column>
        <el-table-column prop="materialQuality" label="材质" align="center" width="150"></el-table-column>
        <el-table-column prop="number" label="数量" align="center" width="80"></el-table-column>
        <el-table-column prop="deliveryDate" label="交货日期" align="center" width="120"></el-table-column>
        <el-table-column label="数量统计" align="center">
          <el-table-column prop="dispatchNumber" label="派工" align="center" width="70"></el-table-column>
          <el-table-column prop="finishedNumber" label="完工" align="center" width="70"></el-table-column>
          <el-table-column prop="workingNumber" label="在产" align="center" width="70"></el-table-column>
          <el-table-column prop="wastedNumber" label="废品" align="center" width="70"></el-table-column>
          <el-table-column prop="pendingNumber" label="待处理" align="center" width="85"></el-table-column>
          <el-table-column prop="waitingNumber" label="待投产" align="center" width="85"></el-table-column>
        </el-table-column>
        <el-table-column prop="state" label="状态" align="center" width="90"></el-table-column>
        <el-table-column prop="remark" label="备注" align="center" min-width="150"></el-table-column>
      </el-table>
    </div>

    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- 创建派工单组件======================================================================================= -->
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <el-button class="ml10" type="primary" @click="openAddingPanel()" v-if="$checkAuth('创建派工单')">添加派工单</el-button>
    <el-button class="ml10" type="primary" @click="previousProduct()" v-if="showQuickSwitch">上一条</el-button>
    <el-button class="ml10" type="primary" @click="nextProduct()" v-if="showQuickSwitch">下一条</el-button>
    <el-button class="ml10" type="primary" @click="back()">返回</el-button>
    <el-button class="ml10" type="primary" @click="initData()">刷新</el-button>
    <div v-show="addingPanelVisible" class="p20-x">
      <div class="mt10 pl10 mb20">
        <span class="bold">选择工艺版本</span>
        <el-select v-model="choosedVersionName" filterable clearable class="ml10" placeholder="选择工艺版本" @change="changeVersion">
          <template v-for="option in versionList">
            <el-option :label="option.versionName" :value="option" :key="option.versionId"></el-option>
          </template>
        </el-select>
        <span class="bold ml20">派工单数量</span>
        <el-input-number v-model="submitData.dispatchNumber" @change="dispatchNumChange" placeholder="派工数量" size="small" class="w110 ml10" :min="0"></el-input-number>
        <el-switch v-model="submitData.cleanBySelf" active-text="自清整" inactive-text="专人清整" active-color="#004098" class="ml20" @change="cleanTypeChange"></el-switch>
        <el-button type="text" icon="el-icon-check" class="ml20" @click="saveDispatch()" :disabled="!choosedVersionName">提交</el-button>
        <el-button type="text" icon="el-icon-close" class="ml20" @click="cancel">取消</el-button>
      </div>
      <el-table border stripe :data="choosedVersionPList">
        <el-table-column prop="sequenceNumber" label="工序号" align="center" width="80"></el-table-column>
        <el-table-column prop="processName" label="工序名称" align="center" width="120"></el-table-column>
        <el-table-column prop="department" label="部门" align="center" width="100"></el-table-column>
        <el-table-column prop="dispatchNumber" label="工序数量" align="center" width="175">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.dispatchNumber" v-if="scope.row.processName != '完工'" size="small" class="w110" :min="0"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="single" label="单双机" align="center" width="100">
          <template slot-scope="scope" v-if="scope.row.processName != '完工'">
            <div v-if="scope.row.department == '加工'">{{ scope.row.single ? '单机' : '双机' }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="quotaHour" label="定额工时" align="center" width="100"></el-table-column>
        <el-table-column prop="workers" label="指派员工" align="center" width="300">
          <template slot-scope="scope">
            <el-select v-if="scope.row.department == '加工'" v-model="scope.row.workers" multiple class="w275" @change="test">
              <template v-for="worker in workerList">
                <el-option :key="worker.id" :label="worker.userName" :value="worker.userName"></el-option>
              </template>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="left" min-width="100">
          <template slot-scope="scope">
            <el-button v-if="scope.row.department == '加工' && scope.row.processName != '完工'" type="text" @click="createCopyDispatch(scope.row)">指派同上</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-col class="w-100percent bold mb5 mt20 remark" style="font-size: 14px">备注 </el-col>
      <br /><br />
      <el-input :readonly="true" v-model="choosedVersionRemark"> </el-input>
    </div>

    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- 派工单列表 ========================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <div class="bold fontSize16 mt20 mb10 ml10">派工单列表</div>
    <div class="ml10">
      <el-collapse accordion v-model="activeCollapseData" @change="collapseChange">
        <template v-for="dispatch in dispatchList">
          <el-collapse-item :name="dispatch.dispatchFormId" :key="dispatch.dispatchFormId">
            <template slot="title">
              <div class="flex justify-content-center">
                <span class="fontSize14 bold">
                  <el-tag class="ml10" size="small" effect="dark" type="success" v-if="dispatch.state == 0">进行中</el-tag>
                  <el-tag class="ml10" size="small" effect="dark" type="info" v-if="dispatch.state == 1">已完工</el-tag>
                  <el-tag class="ml10" size="small" effect="dark" type="danger" v-if="dispatch.state == 2">已终止</el-tag>
                </span>
                <div class="w200"><span class="pl15 fontSize14 bold">派工单号：</span>{{ dispatch.dispatchFormNumber }}</div>
                <div class="w120"><span class="pl15 fontSize14 bold">派工数量：</span>{{ dispatch.dispatchNumber }}</div>
                <div class="w225"><span class="pl15 fontSize14 bold">派工时间：</span>{{ dispatch.createTime }}</div>
                <div :class="dispatch.isEdit ? 'w300' : 'w150'">
                  <span class="pl15 fontSize14 bold">清整方式：</span>
                  <el-switch v-if="dispatch.isEdit" v-model="dispatch.cleanBySelf" active-text="自清整" inactive-text="专人清整" active-color="#004098" class="ml20"></el-switch>
                  <span v-else>{{ dispatch.cleanBySelf ? '自清整' : '专人清整' }}</span>
                </div>
                <div class="w120"><span class="pl15 fontSize14 bold">完工数量：</span>{{ dispatch.finishedNumber }}</div>
                <div class="w225"><span class="pl15 fontSize14 bold">完工时间：</span>{{ dispatch.finishTime }}</div>
              </div>
            </template>
            <el-row>
              <el-button v-show="dispatch.isEdit" type="text" size="small" class="w50 mr20" icon="el-icon-close" @click="dispatch.isEdit = false">取消变更</el-button>
              <el-button
                type="text"
                size="small"
                class="w50"
                :icon="dispatch.isEdit ? 'el-icon-check' : 'el-icon-edit'"
                :disabled="dispatch.formState != '进行中'"
                @click="editDispatch(dispatch)"
                v-if="$checkAuth('修改派工单')"
                >{{ dispatch.isEdit ? '保存' : '变更' }}</el-button
              >
              <el-button
                type="text"
                size="small"
                class="w80"
                icon="el-icon-check"
                :disabled="dispatch.isEdit || ['已完工', '异常终止'].includes(dispatch.formState)"
                v-if="$checkAuth('完工确认')"
                @click="confirmCompleteDispatch(dispatch)"
                >完工确认</el-button
              >
              <el-button
                type="text"
                size="small"
                class="w50"
                icon="el-icon-warning-outline"
                :disabled="dispatch.isEdit || ['已完工', '异常终止'].includes(dispatch.formState)"
                v-if="$checkAuth('终止派工单')"
                @click="terminateDispatch(dispatch)"
                >终止</el-button
              >
              <el-button type="text" size="small" :disabled="dispatch.isEdit" v-if="$checkAuth('创建派工单')" @click="onClickQR(dispatch.dispatchFormId, dispatch.dispatchNumber)"
                >生成二维码</el-button
              >
            </el-row>
            <el-table
              border
              class="mb10"
              :data="dispatch.processList"
              :row-class-name="tableRowClassName"
              :cell-style="cellStyle"
              row-key="sid"
              default-expand-all
              v-show="!dispatch.isEdit"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
            >
              <el-table-column prop="sequenceNumber" label="工序号" fixed="left" align="center" width="70"></el-table-column>
              <el-table-column prop="processState" label="工序状态" fixed="left" align="center" width="80"> </el-table-column>
              <el-table-column prop="processName" label="工序名称" fixed="left" align="center" width="80">
                <template slot-scope="scope">
                  <span v-if="scope.row.paramA < 2">{{ scope.row.processName }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="department" label="部门" align="center" width="70"></el-table-column>
              <el-table-column prop="totalNumber" label="工序数量" align="center" width="80">
                <template slot-scope="scope">
                  <input v-if="scope.row.processState == '未开始' && dispatch.isEdit" class="w50" v-model="scope.row.dispatchNumber" />
                  <span v-else>{{ scope.row.dispatchNumber }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="single" label="单双机" align="center" width="75">
                <template slot-scope="scope" v-if="scope.row.processName != '完工'">
                  <div v-if="scope.row.department == '加工'">{{ scope.row.single ? '单机' : '双机' }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="quotaHour" label="定额工时" align="center" width="80">
                <template slot-scope="scope">
                  <span v-if="scope.row.paramA != 2">{{ scope.row.quotaHour }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="workers" label="指派(完工)人" align="center" min-width="200"></el-table-column>
              <el-table-column prop="finishedNumber" label="完工数量" align="center" width="80"> </el-table-column>
              <el-table-column prop="realWorkHour" label="实动工时" align="center" width="80"></el-table-column>
              <el-table-column label="平均用时" align="center" width="80">
                <template slot-scope="scope">
                  {{ scope.row.finishedNumber == 0 ? 0 : (scope.row.realWorkHour / scope.row.finishedNumber).toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column prop="numWorkQualifiedWork" label="合格" align="center" width="80"></el-table-column>
              <el-table-column prop="numWorkPending" label="待处理" align="center" width="80"></el-table-column>
              <el-table-column prop="numWorkWasteIndustrial" label="工废" align="center" width="80"></el-table-column>
              <el-table-column prop="numWorkWasteMaterial" label="废料" align="center" width="80"></el-table-column>
              <el-table-column prop="waitingNumber" label="未完工" align="center" width="80"></el-table-column>
              <el-table-column label="操作" align="left" fixed="right" min-width="200">
                <template slot-scope="scope">
                  <el-button type="text" size="small" icon="el-icon-s-claim" v-if="scope.row.numberPending > 0" @click="showPenddingDetail(scope.row)">待处理详情</el-button>
                  <!-- 调整工时 -->
                  <el-button v-if="permissionChangeQuotaHour(scope.row)" type="text" size="small" icon="el-icon-s-claim" @click="changeQuotaHour(scope.row)">调整工时 </el-button>
                  <!-- 工序转外协 -->
                  <el-button v-if="permissionToOutsource(scope.row)" type="text" size="small" icon="el-icon-s-claim" @click="outsource(scope.row)">转外 </el-button>
                  <!-- 报验回退 -->
                  <el-button v-if="permissionBackInspection(scope.row)" type="text" size="small" icon="el-icon-s-claim" @click="sendInspectionBack(scope.row)">报验回退</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- ==================================================================================================== -->
            <!-- ==================================================================================================== -->
            <!-- 修改派工单组件======================================================================================= -->
            <!-- ==================================================================================================== -->
            <!-- ==================================================================================================== -->
            <el-table border stripe :data="tempProcessList" row-key="sid" default-expand-all :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" v-show="dispatch.isEdit">
              <el-table-column prop="sequenceNumber" label="工序号" align="center" width="80"></el-table-column>
              <el-table-column prop="processState" label="工序状态" fixed="center" align="center" width="80"></el-table-column>
              <el-table-column prop="processName" label="工序名称" align="center" width="120"></el-table-column>
              <el-table-column prop="department" label="部门" align="center" width="100"></el-table-column>
              <el-table-column prop="dispatchNumber" label="工序数量" align="center" width="175"> </el-table-column>
              <el-table-column prop="single" label="单双机" align="center" width="100">
                <template slot-scope="scope" v-if="scope.row.processName != '完工'">
                  <div v-if="scope.row.department == '加工'">{{ scope.row.single ? '单机' : '双机' }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="quotaHour" label="定额工时" align="center" width="100"></el-table-column>
              <el-table-column prop="workers" label="指派员工" align="center" width="300">
                <template slot-scope="scope">
                  <span v-if="scope.row.state == 0 || scope.row.state == 1">
                    <el-select v-if="scope.row.department == '加工'" v-model="scope.row.workers" multiple class="w275" @change="test">
                      <template v-for="worker in workerList">
                        <el-option :key="worker.id" :label="worker.userName" :value="worker.userName"></el-option>
                      </template>
                    </el-select>
                  </span>
                  <span v-else>{{ scope.row.workers }}</span>
                </template>
              </el-table-column>
              <el-table-column fixed="right" align="left" min-width="100">
                <template slot-scope="scope">
                  <el-button v-if="scope.row.department == '加工' && scope.row.processName != '完工'" type="text" @click="updateCopyDispatch(scope.row)">指派同上</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>
        </template>
      </el-collapse>
    </div>

    <!-- <QR ref="qr"></QR> -->
    <no-data placeholder="还没有派工单，快去添加吧~" v-if="dispatchList.length == 0"></no-data>
    <el-dialog width="400px" title="工时调整" @close="hourDialogClose" :visible="hourDialogVisible">
      <el-form :model="workHour" :rules="rules" label-width="100px">
        <el-form-item label="调试工时" prop="debugHour">
          <el-input v-model="workHour.debugHour" placeholder="请输入调试工时" class="w200"></el-input>
        </el-form-item>
        <el-form-item label="定额工时" prop="quotaHour">
          <el-input v-model="workHour.quotaHour" placeholder="请输入定额工时" class="w200"></el-input>
        </el-form-item>
      </el-form>
      <div style="border-top: 1px solid #eee; padding: 10px 0px; background: #fefefe; text-align: center">
        <el-button type="primary" @click="adjustWorkHour">下一步</el-button>
        <el-button @click="hourDialogClose">取消</el-button>
      </div>
    </el-dialog>
    <!-- 单双机审核弹框 -->
    <el-dialog width="500px" title="单双机审核" @close="singleDialogClose" :visible="singleDialogVisible">
      <h2>{{ singleConfirmMessage }}</h2>
      <br />
      <span>将以此计算工资工时，若相反请选'否'</span>
      <div style="border-top: 1px solid #eee; padding: 10px 0px; background: #fefefe; text-align: center">
        <el-button type="primary" @click="singleConfirm(true)">是</el-button>
        <el-button @click="singleConfirm(false)">否</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import _ from 'lodash'
import {
  qrcodeDispatch,
  getDispatchPV,
  getDispatchDetail,
  createDispatch,
  updateDispatch,
  confirmDispatch,
  stopDispatch,
  getDispatchProductDetail,
  splitDispatchForm,
  changeQuotaHourApi,
  singleDispatch,
  toOutsource,
  sendBackProcess,
  sendInspectionBackApi
} from '@/api/dispatch' // 获取产品上的设计工艺版本
import { getUserWorkerList } from '@/api/interface1' // 获取工人列表接口
import { Notification, Message } from 'element-ui'
import { Component, Vue, Watch } from 'vue-property-decorator'
import { namespace } from 'vuex-class'
import process from '@/store/modules/process'
// import QR from '../qr.vue'

const vuexDispatchDetail = namespace('DispatchDetail')
const vuexNotice = namespace('NewNotice')

@Component({
  components: {}
})
export default class DispatchDetails extends Vue {
  created() {
    this.initData()
    this.submitData.producingId = this.producingId
  }

  initData() {
    this.getProducingDetail()
    this.getDispatchList()
    this.getProcessVersion()
    this.getWorkerList()
  }

  /* **************************************************************************************************** */
  /* **************************************************************************************************** */
  /* 页面预加载数据 BEGIN ************************************************************************************ */
  /* **************************************************************************************************** */
  /* **************************************************************************************************** */

  @vuexDispatchDetail.State producingId

  versionList: any = [] // 产品投产工艺路线版本列表

  // 获取产品投产工艺路线版本列表
  async getProcessVersion() {
    let resp = await getDispatchPV({ producingId: this.producingId }).catch(err => {
      Notification.error(err)
    })
    if (resp) {
      this.versionList = resp.data
    }
  }

  /* ***************** */
  /* 页面预加载数据 END */
  /* ***************** */

  /* **************************************************************************************************** */
  /* **************************************************************************************************** */
  /* 快速派工 切换前一个/后一个产品 BEGIN ****************************************************************** */
  /* **************************************************************************************************** */
  /* **************************************************************************************************** */

  @vuexNotice.State productList: any
  @vuexDispatchDetail.Mutation setProducingId
  showQuickSwitch: boolean = false
  // 查找当前产品的前一个产品
  previousProduct() {
    let pIds = this.productList.flatMap(p => {
      let ids: any = []
      ids.push(p.producingId)
      if (p.children.length > 0) {
        for (let product of p.children) {
          ids.push(product.producingId)
        }
      }
      return ids
    })
    for (let i = 0; i < pIds.length; i++) {
      if (pIds[i] == this.producingId) {
        if (i == 0) {
          this.$alert('当前产品为订单首个产品')
        } else {
          this.setProducingId(pIds[i - 1])
          this.initData()
          this.submitData.producingId = this.producingId
          break
        }
      }
    }
  }
  // 查找当前产品的下一个产品
  nextProduct() {
    let pIds = this.productList.flatMap(p => {
      let ids: any = []
      ids.push(p.producingId)
      if (p.children.length > 0) {
        for (let product of p.children) {
          ids.push(product.producingId)
        }
      }
      return ids
    })
    for (let i = 0; i < pIds.length; i++) {
      if (pIds[i] == this.producingId) {
        if (i == pIds.length - 1) {
          this.$alert('当前产品为订单最后一个产品')
        } else {
          this.setProducingId(pIds[i + 1])
          this.initData()
          this.submitData.producingId = this.producingId
          break
        }
      }
    }
  }

  /* ******************************* */
  /* 快速派工 切换前一个/后一个产品 END */
  /* ******************************* */

  /* **************************************************************************************************** */
  /* **************************************************************************************************** */
  /* 创建派工单 BEGIN ************************************************************************************ */
  /* **************************************************************************************************** */
  /* **************************************************************************************************** */

  addingPanelVisible: boolean = false // 创建派工单 面板可见性控制
  choosedVersionPList: any = [] // 创建派工单 选中的工艺路线版本工序列表
  choosedVersionName: string = '' // 创建派工单 选中的工艺路线版本名称
  choosedVersionRemark: string = '' // 创建派工单 选中的工艺路线版本备注

  // 创建派工单 请求参数
  submitData: any = {
    producingId: '', // 产品生产ID
    versionId: '', // 工艺路线版本ID
    dispatchNumber: 0, // 派工单派工数量
    cleanBySelf: true, // 自清整/专人清整
    processList: [] // 派工工序列表
  }
  // 显示添加派工单面板 并 初始化数据
  openAddingPanel() {
    this.initDateForDispatch()
    this.addingPanelVisible = true
  }
  // 创建派工单 数据初始化
  initDateForDispatch() {
    this.choosedVersionName = ''
    this.curProcessIndex = -1
    this.choosedVersionPList = []
    this.submitData.dispatchNumber = 0
    this.submitData.versionId = ''
    this.submitData.processList = []
    this.activeCollapseData = null
  }

  // 创建派工单 选择工艺路线版本
  changeVersion(version) {
    if (version) {
      this.choosedVersionName = version.versionName
      this.submitData.versionId = version.versionId
      this.choosedVersionRemark = version.remark

      let processList = _.cloneDeep(version.processList)
      processList = processList.map((pItem, pIndex) => {
        this.$set(pItem, 'sid', 'a' + this.dot + pIndex)
        this.$set(pItem, 'dispatchNumber', 0)
        return pItem
      })
      this.choosedVersionPList = processList

      // 默认自清整，如果有清整工序，则专人清整
      this.submitData.cleanBySelf = true
      for (let i = 0; i < processList.length; i++) {
        if (processList[i].processName == '清整') {
          this.submitData.cleanBySelf = false
        }
      }
    } else {
      this.initDateForDispatch()
    }
  }

  //创建派工单 派工数量改变
  dispatchNumChange(value) {
    this.submitData.dispatchNumber = value
    this.choosedVersionPList = this.choosedVersionPList.map(item => {
      item.dispatchNumber = value
      return item
    })
  }

  /* ================================================== */
  /* ================================================== */
  /* 创建派工单 指派同上序 ============================ */
  /* ================================================== */
  /* ================================================== */
  createCopyDispatch(row) {
    for (let i = 1; i < this.choosedVersionPList.length; i++) {
      if (this.choosedVersionPList[i].sequenceId == row.sequenceId) {
        row.workers = this.choosedVersionPList[i - 1].workers
      }
    }
  }

  // 创建派工单 提交请求
  saveDispatch() {
    // 派工单参数校验
    if (!this.submitData.dispatchNumber) {
      Notification.error('派工单数量不能为零！')
      return
    }
    let processList = _.cloneDeep(this.choosedVersionPList)
    for (let i = 0; i < processList.length; i++) {
      this.$set(processList[i], 'processSequenceId', processList[i].sequenceId)
      this.$set(processList[i], 'workers', JSON.stringify(processList[i].workers))
      if (processList[i].department == '加工' && processList[i].workers.length == 0) {
        Notification.error('工序' + (i + 1) + '未指派员工')
        return
      }
    }
    this.submitData.processList = processList
    this.submitDispatchReq(this.submitData)
  }
  async submitDispatchReq(data) {
    let res = await createDispatch(data).catch(err => {
      Notification.error(err)
    })
    if (res) {
      Message.success('新建派工单成功!')
      this.initDateForDispatch()
      this.addingPanelVisible = false
      this.getProducingDetail()
      this.getDispatchList()
    }
  }
  /* ************* */
  /* 创建派工单 END */
  /* ************* */

  /* ==================================================================================================== */
  /* ==================================================================================================== */
  /* 派工单工序操作 BEGIN ================================================================================ */
  /* ==================================================================================================== */
  /* ==================================================================================================== */

  /* ================================================== */
  /* ================================================== */
  /* 派工单工序操作 调整工时 ============================ */
  /* ================================================== */
  /* ================================================== */

  // 是否具有调整工时权限
  // 是否显示调整工时按钮
  permissionChangeQuotaHour(row): boolean {
    // 1. 具有调整工时权限
    // 2. 是工序记录
    // 3. 需要有报验
    return this.$checkAuth('调整工序工时') && (row.paramA == 0 || row.paramA == 1) && row.processName != '完工'
  }

  changeQuotaHour(row) {
    this.$prompt('请输入工序 [ ' + row.processName + ' ] 调整后的定额工时：', '提示', {
      confirmButtonText: '保存',
      cancelButtonText: '取消'
    }).then((value: any) => this.changeQuotaHourReq(row, value.value))
  }
  async changeQuotaHourReq(row, quotaHour) {
    await changeQuotaHourApi({
      dispatchProcessId: row.dispatchProcessId,
      quotaHour: quotaHour
    })
      .then(() => {
        this.$message({ type: 'success', message: '操作成功' })
        row.quotaHour = quotaHour
        console.log('sdfsdfs')
      })
      .catch(err => {
        Notification.error(err)
      })
  }

  /* ================================================== */
  /* ================================================== */
  /* 派工单工序操作 转外协 ============================== */
  /* ================================================== */
  /* ================================================== */
  // 是否具有转外协权限
  // 是否显示转外协按钮
  permissionToOutsource(row): boolean {
    // 1. 具有转外协权限
    // 2. 是厂内加工的工序记录
    // 3. 需要未开始或进行中
    return this.$checkAuth('工序转外协') && row.department == '加工' && row.paramA < 2 && row.state < 2
  }
  outsource(row) {
    console.log('自制转外')
    console.log(row)
    let warnMessage = '确认将工序' + row.sequenceNumber + '-【' + row.processName + '】自制转外协？'
    this.$confirm(warnMessage, '操作提示', {
      cancelButtonText: '取消',
      confirmButtonText: '确定',
      type: 'warning'
    })
      .then(() => {
        this.toOutsourceReq(row.dispatchProcessId)
      })
      .catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
  }
  async toOutsourceReq(id) {
    let param = {
      dispatchProcessId: id
    }
    let res = await toOutsource(param).catch(err => {
      Notification.error(err)
    })
    if (res) {
      this.getDispatchList()
      this.$message({
        type: 'success',
        message: '修改成功'
      })
    }
  }

  /* ================================================== */
  /* ================================================== */
  /* 派工单工序操作 报验回退 ============================ */
  /* ================================================== */
  /* ================================================== */

  // 是否具有报验回退权限
  // 是否显示操作按钮
  permissionBackInspection(row): boolean {
    // 1. 拥有报验回退权限
    // 2. state == 5 报验已确认（已完成）
    // 3. paramA == 0 || 2 工序报验一体记录 或 报验记录
    // 4. 所在派工单状态为 进行中
    // 5. 要有工序数量，如果 工序数量 为 0 会是自动完工的工序 没有报验
    let formState = -1
    for (let dispatch of this.dispatchList) {
      if (dispatch.dispatchFormId == row.dispatchFormId) {
        formState = dispatch.state
        break
      }
    }

    return this.$checkAuth('管理者工序回退') && row.state == 5 && (row.paramA == 0 || row.paramA == 2) && row.processName != '完工' && formState == 0 && row.dispatchNumber > 0
  }

  // 报验回退
  sendInspectionBack(row) {
    this.$confirm('将回退员工报验，需要其重新填报', '操作提示', {
      cancelButtonText: '取消',
      confirmButtonText: '确定',
      type: 'warning'
    })
      .then(() => {
        this.sendInspectionBackReq(row.dispatchProcessId)
      })
      .catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
  }
  async sendInspectionBackReq(id) {
    let res = await sendInspectionBackApi({ dispatchProcessId: id }).catch(err => {
      Notification.error(err)
    })
    if (res) {
      this.initData()
      this.$message({
        type: 'success',
        message: '回退成功'
      })
    }
  }

  /* ==================================================================================================== */
  /* ==================================================================================================== */
  /* 派工单工序操作 END ================================================================================== */
  /* ==================================================================================================== */
  /* ==================================================================================================== */

  /* **************************************************************************************************** */
  /* **************************************************************************************************** */
  /* 派工单变更 BEGIN ************************************************************************************ */
  /* **************************************************************************************************** */
  /* **************************************************************************************************** */

  /* ================================================== */
  /* ================================================== */
  /* 派工单变更 指派同上序 ============================ */
  /* ================================================== */
  /* ================================================== */
  updateCopyDispatch(row) {
    for (let i = 1; i < this.tempProcessList.length; i++) {
      if (this.tempProcessList[i].dispatchProcessId == row.dispatchProcessId) {
        row.workers = this.tempProcessList[i - 1].workers
      }
    }
  }

  /* **************************************************************************************************** */
  /* **************************************************************************************************** */
  /* BEGIN ************************************************************************************ */
  /* **************************************************************************************************** */
  /* **************************************************************************************************** */

  tableRowClassName({ row, rowIndex }) {
    if (row.parentId == 0) {
      return 'success-row'
    }
    return ''
  }
  cellStyle({ row, column, rowIndex, columnIndex }) {
    if (['合格', '完工数量', '未完工'].indexOf(column.label) > -1 && (row.paramA == 0 || row.paramA == 1)) {
      return 'font-weight: bold;'
    }
  }

  /* **************************************************************************************************** */
  /* **************************************************************************************************** */
  /* BEGIN ************************************************************************************ */
  /* **************************************************************************************************** */
  /* **************************************************************************************************** */
  test(value) {
    console.log('===test value ===')
    console.log(value)
  }
  notInTotalForm(row) {
    for (let i = 0; i < this.dispatchList.length; i++) {
      let form = this.dispatchList[i]
      if (form.hasSplit) {
        // 说明是汇总单
      }
    }
  }
  workerList: any = [{ id: 0, userName: '工人' }]
  productDetil: any = [
    {
      drawingNumber: '',
      productName: '',
      materialQuality: '',
      number: '',
      deliveryDate: '',
      finishedNumber: '',
      workingNumber: '',
      waitingNumber: '',
      state: '',
      remark: ''
    }
  ]
  hourDialogVisible: any = false
  curProcessIndex: any = -1 // 用来在添加设备/人员的时候找到该工序
  curEquipment: any = null // 用来添加指派人的时候保存设备对象
  addDispatch: any = false // 记录当前是否处于添加派工单状态
  dot: any = '_'

  dispatchList: any = []
  activeCollapseData: any = null
  isEdit: any = false // false:变更 true:保存
  noSingleReview: any = true // 没有需要单双机审核的工序
  tempProcessList: any = []
  tempProcessIndex: any = -1
  tempVersion: any = []
  name: any = 'distribute'

  @vuexDispatchDetail.State currentDispatchForm
  @vuexDispatchDetail.State currentVersionForm
  @vuexDispatchDetail.Mutation setCurrentDispatchForm
  @vuexDispatchDetail.Mutation setCurrentVersionForm

  /**
   * 查看待处理详情
   */
  showPenddingDetail(row) {
    console.log('===查看待处理详情===')
    console.log(row)

    this.$router.push({
      name: 'menuA1Inspection',
      params: {
        from: 'dispatch',
        inspectionId: row.inspectionId,
        inspectionState: row.inspectionState
      }
    })
  }
  /**
   * 是否显示回退记录
   */
  whetherShowBackBtn(row) {
    if (row.paramA == 2 && row.state == 5) {
      // 判断父工序是否正在进行中
      for (let i = 0; i < this.dispatchList.length; i++) {
        if (this.dispatchList[i].dispatchFormId == row.dispatchFormId) {
          for (let j = 0; j < this.dispatchList[i].processList.length; j++) {
            if (this.dispatchList[i].processList[j].dispatchProcessId == row.parentId) {
              if (this.dispatchList[i].processList[j].state == 1) {
                return true
              }
            }
          }
        }
      }
    }
    return false
  }

  /**
   * 调整已完工工序的工时
   */
  inspRecord: any = {}
  workHour: any = {
    debugHour: 0,
    quotaHour: 0
  }
  rules: any = {
    debugHour: [{ required: true, pattern: /^[0-9]+([.]{1}[0-9]{1})?$/, message: '请填写整数或1位小数', trigger: 'change' }],
    quotaHour: [{ required: true, pattern: /^[0-9]+([.]{1}[0-9]{1})?$/, message: '请填写整数或1位小数', trigger: 'change' }]
  }
  async adjustWorkHour() {
    let param = {
      dispatchProcessId: this.inspRecord.dispatchProcessId,
      debugHour: this.workHour.debugHour,
      quotaHour: this.workHour.quotaHour
    }
    let res = await changeQuotaHourApi(param).catch(err => {
      Notification.error(err)
    })
    if (res) {
      this.initData()
      this.$message({
        type: 'success',
        message: '修改成功'
      })
      this.hourDialogClose()
    }
  }
  hourDialogShow(row) {
    this.inspRecord = row
    this.hourDialogVisible = true
  }
  hourDialogClose() {
    this.hourDialogVisible = false
  }

  sendBack(row) {
    this.$confirm('将回退整道工序，需重新填报', '操作提示', {
      cancelButtonText: '取消',
      confirmButtonText: '确定',
      type: 'warning'
    })
      .then(() => {
        this.sendBackApi(row)
      })
      .catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
  }
  async sendBackApi(row) {
    let param = {
      dispatchProcessId: row.dispatchProcessId
    }
    let res = await sendBackProcess(param).catch(err => {
      Notification.error(err)
    })
    if (res) {
      this.getDispatchList()
      this.$message({
        type: 'success',
        message: '退回成功'
      })
    }
  }

  /**
   * 拆单
   */
  splitForm(row) {
    console.log('当前工序已完工数量：' + row.finishedNumber)
    console.log('当前工序：')
    console.log(row)
    this.$prompt('请输入拆单流转数量', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /\d{1,4}/,
      inputErrorMessage: '请输入数字'
    })
      .then((e: any) => {
        // 拆单数量约束：不能超过已完工报验的合格数量
        let splitNumber = e.value
        console.log('需要拆单流转数量：' + splitNumber)
        if (typeof row.children == 'undefined' || row.children == null) {
          Message.warning('完工数量为0，没有待流转数量')
        } else if (!/(^[1-9]\d*$)/.test(splitNumber)) {
          Message.warning('请输入正整数！')
        } else {
          var finishedQualified = 0
          for (let i = 0; i < row.children.length; i++) {
            finishedQualified += Number(row.children[i].numWorkQualifiedWork)
          }
          if (splitNumber > finishedQualified) {
            console.log('拆单流转数量不能多于已完工合格数量')
            Message.warning('拆单流转数量不能多于已完工合格数量')
          } else {
            // 发起拆单请求
            this.splitFormApi({ dispatchFormId: row.dispatchFormId, splitNumber: e.value })
          }
        }
      })
      .catch(() => {})
  }
  async splitFormApi(param) {
    let res = await splitDispatchForm(param).catch(err => {
      Notification.error(err)
    })
    if (res) {
      this.$message({
        type: 'success',
        message: '拆单成功'
      })
      // 重新刷新页面
      this.initData()
    }
  }

  /**
   * 单双机审核
   */
  singleDialogVisible: boolean = false
  singleConfirmRecord: any = {}
  singleConfirmMessage: string = ''
  singleDialogShow(row) {
    this.singleConfirmRecord = row
    this.singleDialogVisible = true
    let single = row.singleFinish ? '单机' : '双机'
    this.singleConfirmMessage = '确认工序 [' + row.processName + '] 由' + row.workerName + ' [' + single + '] 执行?'
  }
  singleDialogClose() {
    this.singleDialogVisible = false
  }
  // singleConfirm(row) {；
  //   let single = row.singleFinished ? '单机' : '双机'
  //   let message = '确认工序 [' + row.processName + '] 由' + row.workerName + ' [' + single + '] 执行?'
  //   this.$confirm("将以此计算工资工时，若相反请选'否'", message, {
  //     cancelButtonText: '否',
  //     confirmButtonText: '是',
  //     type: 'warning',
  //     closeOnClickModal: false,
  //     closeOnPressEscape: false,
  //     closeOnHashChange: false
  //   })
  //     .then(() => {
  //       this.singleConfirmApi(row, true)
  //     })
  //     .catch(() => {
  //       this.singleConfirmApi(row, false)
  //     })
  // }
  async singleConfirm(result: boolean) {
    let res = await singleDispatch({
      dispatchProcessId: this.singleConfirmRecord.dispatchProcessId,
      result: result
    }).catch(err => {
      Notification.error(err)
    })
    if (res) {
      // 重新刷新页面
      this.initData()
      this.singleDialogClose()
    }
  }

  /**
   * 生命周期函数
   */
  mounted() {
    let from = this.$route.params.from
    console.log('路由来源')
    console.log(from)
    console.log(this.currentDispatchForm)
    console.log(this.currentVersionForm)
    if (from == 'list') {
      // 从路线单列表页面进入 默认打开对应派工单
      this.activeCollapseData = this.$route.params.formId
    } else if (from == 'notice-cards') {
      // 从生产通知派工页面进入，展示快速切换产品按钮
      this.showQuickSwitch = true
    }
  }

  /**
   * 获取产品数据详情
   */
  async getProducingDetail() {
    let res = await getDispatchProductDetail({ producingId: this.producingId }).catch(err => {
      Notification.error(err)
    })
    if (res) {
      let product: any = res.data
      this.$set(product, 'noticeNumber', this.$route.params.noticeNumber)
      this.$set(product, 'wNumber', this.$route.params.workingNumber)
      this.productDetil = []
      this.productDetil.push(product)
    }
  }

  /**
   * 获取产品派工路线单数据
   */
  async getDispatchList() {
    let res = await getDispatchDetail({ producingId: this.producingId }).catch(err => {
      Notification.error(err)
    })
    if (res) {
      this.dispatchList = res.data
      this.resetSidDispatch()
    }
  }

  /**
   * 获取派工工人列表
   */
  async getWorkerList() {
    let res = await getUserWorkerList().catch(err => {
      Notification.error(err)
    })
    if (res) {
      this.workerList = res.data
    }
  }
  /**
   * 切换路线单面板时绑定对应formId
   */
  collapseChange(val) {
    this.isEdit = false
    // 传入的val是当前折叠面板绑定的dispatchFormId
    // 根据dispatchFormId确定当前的dispatchForm
    // 根据versionId确定当前的工艺版本
    var currentDispatchForm = this.dispatchList.filter(form => form.dispatchFormId == val)
    this.setCurrentDispatchForm(currentDispatchForm[0])
    var currentVersionForm = this.versionList.filter(form => form.dispatchFormId == currentDispatchForm.versionId)
    this.setCurrentVersionForm(currentVersionForm[0])
  }

  back() {
    this.$router.go(-1)
  }

  cleanTypeChange(value) {
    console.log('清整选择：' + value)
    // 如果选择自清整，需要判断工序中是否有清整工序，如果有清整工序仍派人自清整，则需要弹框确认
    if (value == true) {
      for (let i = 0; i < this.choosedVersionPList.length; i++) {
        if (this.choosedVersionPList[i].processName == '清整') {
          this.$confirm('工艺表中有清整工序，是否指派为自清整？', '操作提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              this.submitData.cleanBySelf = true
            })
            .catch(() => {
              this.submitData.cleanBySelf = false
            })
        }
      }
    }
  }
  addEquipment(data) {
    console.log('===添加设备===')
    console.log(data)

    let equip = _.cloneDeep(data)
    if (typeof this.choosedVersionPList[this.curProcessIndex].children == 'undefined') {
      this.$set(this.choosedVersionPList[this.curProcessIndex], 'children', [])
    }
    let flag = false
    this.choosedVersionPList[this.curProcessIndex].children.forEach(item => {
      if (item.equipment === data.equipment) {
        flag = true
      }
    })
    if (flag) {
      Message.warning('请勿添加重复设备!')
      return
    }
    let eIndex = this.choosedVersionPList[this.curProcessIndex].children.length
    equip.sid = 'b' + this.dot + this.curProcessIndex + this.dot + eIndex
    this.choosedVersionPList[this.curProcessIndex].children.push(_.cloneDeep(equip))
  }
  delEquipment(sid) {
    let info = sid.split(this.dot) // info=[a:工序列表的Index;b:设备的index;c:工人的index]
    this.choosedVersionPList[info[1]].children.splice(info[2], 1) // 删除设备
    this.resetSid()
  }
  addPerson(data) {
    console.log('===添加指派人员===')
    console.log(data)
    let person = _.cloneDeep(data)
    if (typeof this.curEquipment.children == 'undefined') {
      this.$set(this.curEquipment, 'children', [])
    }
    let flag = false
    this.curEquipment.children.forEach(item => {
      if (item.workerName === data.workerName) {
        flag = true
      }
    })
    if (flag) {
      Message.warning('请勿添加重复人员!')
      return
    }
    let pIndex = this.curEquipment.sid.split(this.dot)[1]
    let eIndex = this.curEquipment.sid.split(this.dot)[2]
    let wIndex = this.curEquipment.children.length
    person.sid = 'c' + this.dot + pIndex + this.dot + eIndex + this.dot + wIndex
    this.curEquipment.children.push(person)
  }
  delPerson(sid) {
    let info = sid.split(this.dot)
    this.choosedVersionPList[info[1]].children[info[2]].children.splice(info[3], 1)
    this.resetSid()
  }
  resetSid() {
    this.choosedVersionPList = this.choosedVersionPList.map((item, index) => {
      if (item.children) {
        item.children = item.children.map((cItem, cIndex) => {
          if (cItem.children) {
            cItem.children = cItem.children.map((wItem, wIndex) => {
              wItem.sid = 'c' + this.dot + index + this.dot + cIndex + this.dot + wIndex
              return wItem
            })
          }
          cItem.sid = 'b' + this.dot + index + this.dot + cIndex
          return cItem
        })
      }
      return item
    })
  }
  resetSidDispatch() {
    this.dispatchList = this.dispatchList.map(dItem => {
      this.$set(dItem, 'isEdit', false)
      dItem.processList = dItem.processList.map((item, index) => {
        if (item.processName == '完工') {
          item.finishedNumber = ''
          item.waitingNumber = ''
          item.numWorkQualifiedWork = ''
          item.numWorkQualifiedDebug = ''
          item.numWorkPending = ''
          item.numWorkWasteMaterial = ''
          item.numWorkWasteIndustrial = ''
          item.realWorkHour = ''
        }
        if (item.processState == '单双机审核') {
          this.noSingleReview = false
        }
        if (item.children && item.children.length) {
          item.children = item.children.map((cItem, cIndex) => {
            if (cItem.children) {
              cItem.children = cItem.children.map((wItem, wIndex) => {
                wItem.sid = 's' + this.dot + index + this.dot + cIndex + this.dot + wIndex
                return wItem
              })
            }
            cItem.sid = 'c' + this.dot + index + this.dot + cIndex
            return cItem
          })
          item.sid = 'b' + this.dot + index + this.dot + index
        } else {
          this.$delete(item, 'children')
        }
        return item
      })
      return dItem
    })
  }
  resetSidTempDispatch() {
    this.tempProcessList = this.tempProcessList.map((item, index) => {
      if (item.children && item.children.length) {
        item.children = item.children.map((cItem, cIndex) => {
          if (cItem.children) {
            cItem.children = cItem.children.map((wItem, wIndex) => {
              wItem.sid = 'c' + this.dot + index + this.dot + cIndex + this.dot + wIndex
              return wItem
            })
          }
          cItem.sid = 'b' + this.dot + index + this.dot + cIndex
          return cItem
        })
      }
      return item
    })
  }
  addTempEquipment(data) {
    let equip = _.cloneDeep(data)
    if (typeof this.tempProcessList[this.tempProcessIndex].children == 'undefined') {
      this.$set(this.tempProcessList[this.tempProcessIndex], 'children', [])
    }
    // 判断添加设备不重复
    let flag = false
    this.tempProcessList[this.tempProcessIndex].children.forEach(item => {
      if (item.equipment === data.equipment) {
        flag = true
      }
    })
    if (flag) {
      Message.warning('请勿添加重复设备!')
      return
    }
    let eIndex = this.tempProcessList[this.tempProcessIndex].children.length
    equip.sid = 'b' + this.dot + this.tempProcessIndex + this.dot + eIndex
    equip.canEdit = true
    this.tempProcessList[this.tempProcessIndex].children.push(_.cloneDeep(equip))
  }
  delTempEquipment(sid) {
    let info = sid.split(this.dot) // info=[a:工序/b:设备/c:工人,工序列表的Index,设备的index,工人的index}
    this.tempProcessList[info[1]].children.splice(info[2], 1) // 删除设备
    this.resetSidTempDispatch()
  }
  addTempPerson(data) {
    let person = _.cloneDeep(data)
    if (typeof this.curEquipment.children == 'undefined') {
      this.$set(this.curEquipment, 'children', [])
    }
    let flag = false
    this.curEquipment.children.forEach(item => {
      if (item.workerName === data.workerName) {
        flag = true
      }
    })
    if (flag) {
      Message.warning('请勿添加重复人员!')
      return
    }
    let pIndex = this.curEquipment.sid.split(this.dot)[1]
    let eIndex = this.curEquipment.sid.split(this.dot)[2]
    let wIndex = this.curEquipment.children.length
    person.sid = 'c' + this.dot + pIndex + this.dot + eIndex + this.dot + wIndex
    person.canEdit = true
    this.curEquipment.children.push(person)
  }
  delTempPerson(sid) {
    let info = sid.split(this.dot)
    this.tempProcessList[info[1]].children[info[2]].children.splice(info[3], 1)
    this.resetSidTempDispatch()
  }

  close(done) {
    if (this.choosedVersionName) {
      this.$confirm(`您还有未提交的派工单信息，退出将不会保存该信息，是否确认退出？`, '退出提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.initDateForDispatch()
          this.versionList = []
          this.dispatchList = []
          this.addingPanelVisible = false
          this.hourDialogVisible = false
          done()
        })
        .catch(() => {})
    } else {
      this.initDateForDispatch()
      this.versionList = []
      this.dispatchList = []
      this.addingPanelVisible = false
      this.hourDialogVisible = false
      done()
    }
  }

  /**
   * 点击取消编辑新建的派工单
   * 清空数据 关闭组件
   */
  cancel() {
    this.initDateForDispatch()
    this.addingPanelVisible = false
  }

  // 变更派工单--变更条件(formState==派工异常)--可变更内容(未开始的工序的工序数量)
  async editDispatch(dispatch) {
    if (dispatch.isEdit) {
      // 点击保存
      this.submitData.dispatchFormId = dispatch.dispatchFormId
      this.submitData.producingId = dispatch.producingId
      this.submitData.versionId = dispatch.versionId
      this.submitData.cleanBySelf = dispatch.cleanBySelf // 是否有必要修改？？
      this.submitData.processList = this.tempProcessList.filter(item => {
        if (item.workers != null) item.workers = JSON.stringify(item.workers)
        return item.processState == '未开始' || item.processState == '进行中'
      })
      let res = await updateDispatch(this.submitData).catch(err => {
        console.log('变更不成功', err)
        Notification.error(err)
        this.tempProcessList = this.tempProcessList.map((pItem, pIndex) => {
          if (pItem.processState == '未开始' || pItem.processState == '进行中') {
            pItem.workers = JSON.parse(pItem.workers)
          }
          return pItem
        })
      })
      if (res) {
        dispatch.isEdit = !dispatch.isEdit
        this.getDispatchList()
      }
    } else {
      // 点击变更按钮
      this.tempProcessList = _.cloneDeep(dispatch.processList)
      // 设置'canEdit' 用来判断哪些数据可以变更
      this.tempProcessList = this.tempProcessList.map((pItem, pIndex) => {
        if (pItem.processState == '未开始' || pItem.processState == '进行中') {
          // pItem.canEdit = true
          // if (pItem.children) {
          //   pItem.children = pItem.children.map(eItem => {
          //     eItem.canEdit = true
          //     if (eItem.children) {
          //       eItem.children = eItem.children.map(wItem => {
          //         wItem.canEdit = true
          //         return wItem
          //       })
          //     }
          //     return eItem
          //   })
          // }
          pItem.workers = JSON.parse(pItem.workers)
        }
        return pItem
      })
      // 设置变更后可选的设备和人员列表
      this.tempVersion = this.versionList.find(item => {
        return item.versionId == dispatch.versionId
      })
      // 设置变更后可选的设备和人员列表
      if (this.tempVersion.processList) {
        this.tempVersion.processList.forEach((item, index) => {
          if (item.equipmentList) {
            this.tempProcessList[index].equipmentList = item.equipmentList
            item.equipmentList.forEach((eItem, eIndex) => {
              this.tempProcessList[index].children.forEach((cItem, cIndex) => {
                if (eItem.equipHourId == cItem.equipHourId) {
                  cItem.workerList = eItem.workerList
                }
              })
            })
          }
        })
      }
      dispatch.isEdit = !dispatch.isEdit
    }
  }

  async confirmCompleteDispatch(dispatch) {
    let flag = true
    dispatch.processList.forEach(item => {
      if (item.state == 0) {
        flag = false // 有未开始的工序
        return
      }
    })
    if (flag) {
      let res = await confirmDispatch({ dispatchFormId: dispatch.dispatchFormId }).catch(err => {
        Notification.error(err)
      })
      if (res) {
        Message.success('已确认完工!')
        this.getProducingDetail()
        this.getDispatchList()
      }
    } else {
      Notification.error('还有未开始的工序，不予完工')
    }
  }

  terminateDispatch(dispatch) {
    const stopParam = {
      dispatchFormId: Number(dispatch.dispatchFormId),
      remark: ''
    }
    this.$prompt('请输入事由', `终止派工单${dispatch.dispatchFormNumber}`, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then((value: any) => {
        console.log('点击了确定')
        stopParam.remark = value.value
        this.onStopDispatch(stopParam)
      })
      .catch(() => {
        console.log('点击了取消')
        this.$message({
          type: 'info',
          message: '取消终止'
        })
      })
    // this.$confirm(`是否确认终止派工单${dispatch.dispatchFormNumber}?`, '操作提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(async () => {
    //     let res = await stopDispatch({dispatchFormId: dispatch.dispatchFormId}).catch(err => {
    //       Notification.error(err)
    //     })
    //     if(res) {
    //       Message.success('已终止派工单!')
    //       this.getDispatchList()
    //     }
    //   }).catch(() => {})
  }

  async onStopDispatch(stopParam) {
    let res = await stopDispatch(stopParam).catch(err => {
      Notification.error(err)
    })
    if (res) {
      Message.success('已终止派工单!')
      this.getDispatchList()
    }
  }

  onClickQR(id, dispatchNumber) {
    window.open('/dispatch/qrcode?dispatchFormId=' + id)
    // this.getQRCode(id);
    // this.$refs.qr.open(id, dispatchNumber)
  }
  async getQRCode(id) {
    let res = await qrcodeDispatch({ dispatchFormId: id })
      .then(res => {
        var filename = res.headers //下载后文件名
        filename = filename['content-disposition']
        filename = decodeURI(filename.split(';')[1].split('filename=')[1])
        var blob = new Blob([res.data], { type: 'image/png' })
        var downloadElement = document.createElement('a')
        var href = URL.createObjectURL(blob) //创建下载的链接
        downloadElement.href = href
        downloadElement.download = filename
        document.body.appendChild(downloadElement)
        downloadElement.click() //点击下载
        document.body.removeChild(downloadElement) //下载完成移除元素
        URL.revokeObjectURL(href) //释放掉blob对象
      })
      .catch(err => {
        console.log('qrcode err')
        console.log(err)
      })
  }

  /**
   * 为了selenium测试绑定元素ID
   */
  bindIdSelectEquipment(row) {
    let id = 'selectD4Equipment' + row.sequenceNumber
    return id
  }

  bindIdOptionEquipment(row, item) {
    let id = 'optionD4Equipment' + row.sequenceNumber + item.equipment
    return id
  }

  bindIdSelectWorker(row) {
    let id = 'selectD4Worker' + row.sid
    return id
  }

  bindIdOptionWorker(row, index) {
    let id = 'optionD4Worker' + row.sid + index
    return id
  }
}
</script>

<style lang="scss">
.dispatch-details-panel {
  padding: 10px 10px 0 10px;
}
.distribute-dialog {
  .el-dropdown-menu {
    min-width: 100px !important;
  }
  .w110 {
    width: 110px;
  }
  .el-dialog {
    min-height: 200px;
  }
  .el-switch__label.is-active > span {
    font-weight: bold;
    font-size: 18px;
  }
}
</style>
